package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springblade.common.utils.CommonUtil;
import org.springblade.common.utils.PoiExcelUtil;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.entity.*;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.Building;
import org.springblade.modules.admin.enums.ElevatorUseTypeEnum;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.ElevatorVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 电梯明显控制层
 *
 * @author zcc
 * @version 1.0
 * @date 2021/4/12 15:42
 */
@RestController
@RequestMapping("/admin/elevator/detail")
@RequiredArgsConstructor
@Api(tags = "电梯扩展信息管理")
public class ElevatorDetailController {

	private final IElevatorDetailService elevatorDetailService;

	private final BuildingService buildingService;

	private final ElevatorService elevatorService;

	private final BuildingElevatorTemplateService buildingElevatorTemplateService;
	private final BuildingElevatorTemplateReleService buildingElevatorTemplateReleService;

	@ApiOperation("下载明细")
	@PostMapping("down/excel/detail")
	public void downExcelDetail(HttpServletResponse response, @RequestBody ElevatorVO elevator) throws IOException {
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList
				("项目名称", "项目地址", "电梯位置","电梯别名", "设备代码","电梯快速识别代码", "电梯品牌", "单位内编号", "登记证编号",
					"额定速度", "额定载重量", "层", "站", "门","电梯状态","年审类型");
			rows.add(title);
			elevatorDetailService.downExcelDetail(elevator, rows);
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			CommonUtil.setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}

	}

	@ApiOperation("下载电梯模板")
	@PostMapping("down/elevator/template")
	public void downElevatorTemplate(HttpServletResponse response, @ApiParam(value = "电梯模板id", required = true) @RequestParam("elevatorTemplateId") Long elevatorTemplateId
		,@ApiParam(value = "电梯设备类型", required = true) @RequestParam("elevatorUseType") Integer elevatorUseType) {
		elevatorDetailService.downElevatorTemplate(response, elevatorTemplateId,elevatorUseType);
	}


	@ApiOperation("excel上传")
	@PostMapping("upload/excel")
	public R<Map<String, Object>> uploadExcel(@RequestParam("file") MultipartFile file, @RequestParam("buildingId") Long buildingId,
	@RequestParam("elevatorUseType") Integer elevatorUseType) throws IOException {
		Building building = buildingService.getById(buildingId);
		if (building == null) {
			return R.fail("不存在的小区");
		}

		if (file.isEmpty()) {
			return R.fail("上传文件不能为空");
		}

		Workbook wb = null;
		try {
			wb = WorkbookFactory.create(file.getInputStream());
		} catch (InvalidFormatException e) {
			return  R.fail("请使用正确的电梯模板导入电梯");
		}
		Sheet sheet = wb.getSheetAt(0);

		Long elevatorTemplateId = null;
		try {
			// sheetName作为电梯模板id
			elevatorTemplateId = Func.toLong(sheet.getSheetName());
		} catch (NumberFormatException e) {
			return  R.fail("请使用正确的电梯模板导入电梯");
		}

		List<Map<String, Object>> readAll = PoiExcelUtil.readExcel(wb, 0, 2, 3, 0);
		if (readAll.size() == 0) {
			return R.fail("上传文件不能为空");
		}

		Map<String, Object> resultMap = elevatorDetailService.uploadExcel(readAll, buildingId, elevatorTemplateId,elevatorUseType);
		return R.data(resultMap);
	}

	@ApiOperation("下载电梯导入错误数据")
	@PostMapping("down/err/elevator/excel")
	public void downErrElevatorExcel(HttpServletResponse response,
									 @ApiParam(value = "电梯模板id", required = true) @RequestParam("elevatorTemplateId") Long elevatorTemplateId,
									 @ApiParam(value = "项目id", required = true) @RequestParam("buildingId") Long buildingId,
									 @ApiParam(value = "电梯设备类型", required = true) @RequestParam("elevatorUseType") Integer elevatorUseType) {
		elevatorDetailService.downErrElevatorExcel(response, elevatorTemplateId, buildingId,elevatorUseType);
	}

	/**
	 * @return 电梯用途分类列表
	 * @Author lsay
	 * @Description {
	 * 获取电梯用途分类
	 * }
	 * @Date 9:30 2021/8/27
	 **/
	@GetMapping("/useType")
	public R<?> userType() {
		return R.data(ElevatorUseTypeEnum.toList());
	}


	@ApiOperation("初始化数据上传")
	@PostMapping("upload/init")
	public R<String> init(@RequestParam("file") MultipartFile file) throws IOException {
		ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
		List<List<Object>> readAll = reader.read();
		readAll.remove(0);
		final List<Elevator> elevatorList = elevatorService.list();
		final List<ElevatorDetail> detailList = elevatorDetailService.list();
		final Map<Long, List<Elevator>> elevatorMap = elevatorList.stream().collect(Collectors.groupingBy(Elevator::getId));
		final Map<Long, List<ElevatorDetail>> elevatorDetailMap = detailList.stream().collect(Collectors.groupingBy(ElevatorDetail::getElevatorId));


		final List<BuildingElevatorTemplate> templateList = buildingElevatorTemplateService.list();

		final List<BuildingElevatorTemplateRele> templateReles = buildingElevatorTemplateReleService.list();

		//处理一级模板
		for (int i = 0; i < readAll.size(); i++) {
			final Map<Long, List<BuildingElevatorTemplate>> listMap = templateList.stream().collect(Collectors.groupingBy(BuildingElevatorTemplate::getBuildingId));
			final Map<Long, List<BuildingElevatorTemplateRele>> templateRelesMap = templateReles.stream().collect(Collectors.groupingBy(BuildingElevatorTemplateRele::getBuildingId));

			List<Object> objects = readAll.get(i);
			Long buildingId = Convert.toLong(objects.get(0));
			Long elevatorId = Convert.toLong(objects.get(1));
			String tenantId = Convert.toStr(objects.get(2));
			String templateName = Convert.toStr(objects.get(3));
			List<BuildingElevatorTemplate> buildingElevatorTemplates = listMap.get(buildingId);
			BuildingElevatorTemplate buildingElevatorTemplate = null;
			if (buildingElevatorTemplates == null) {
				buildingElevatorTemplate = new BuildingElevatorTemplate();
				buildingElevatorTemplate.setBuildingId(buildingId);
				buildingElevatorTemplate.setLevel(templateName.split("/").length);
				buildingElevatorTemplate.setName(templateName);
				buildingElevatorTemplate.setTenantId(tenantId);
				buildingElevatorTemplateService.save(buildingElevatorTemplate);
				templateList.add(buildingElevatorTemplate);
			} else {
				for (BuildingElevatorTemplate buildingElevatorTemplate1 : buildingElevatorTemplates) {
					if (templateName.equals(buildingElevatorTemplate1.getName()) && tenantId.equals(buildingElevatorTemplate1.getTenantId())) {
						buildingElevatorTemplate = buildingElevatorTemplate1;
						break;
					}
				}
			}

			if (buildingElevatorTemplate == null) {
				continue;
			}
			Elevator elevator = elevatorMap.get(elevatorId).get(0);
			ElevatorDetail elevatorDetail = elevatorDetailMap.get(elevatorId).get(0);
			elevator.setTemplateId(buildingElevatorTemplate.getId());
			if ("#/无".equals(templateName)) {
				final String[] split = templateName.split("/");
				final List<String> names = Arrays.asList(split);


			} else if ("无".equals(templateName)) {
				BuildingElevatorTemplateRele buildingElevatorTemplateRele = new BuildingElevatorTemplateRele();
				buildingElevatorTemplateRele.setBuildingId(buildingId);
				buildingElevatorTemplateRele.setTemplateName(templateName);
				buildingElevatorTemplateRele.setTemplateNum(elevatorDetail.getElevatorAddress());
				buildingElevatorTemplateRele.setTemplateId(buildingElevatorTemplate.getId());
				buildingElevatorTemplateRele.setLevel(1);
				buildingElevatorTemplateRele.setTenantId(tenantId);
				buildingElevatorTemplateReleService.save(buildingElevatorTemplateRele);
				elevator.setReleIds(buildingElevatorTemplateRele.getId().toString());
			} else if ("幢/单元/无".equals(templateName)) {

			} else if ("幢/无".equals(templateName)) {

			} else if ("栋".equals(templateName)) {

			} else if ("栋/单元/无".equals(templateName)) {

			} else if ("栋/梯/无".equals(templateName)) {

			} else if ("栋/梯/无".equals(templateName)) {

			} else if ("栋/无".equals(templateName)) {

			} else if ("号/座".equals(templateName)) {
			} else if ("期/栋/座".equals(templateName)) {
			} else if ("期/栋/座/无".equals(templateName)) {
			} else if ("无/幢/无".equals(templateName)) {
			} else if ("无/座/无".equals(templateName)) {
			}
			elevatorService.updateById(elevator);
		}
		return R.data("初始化数据成功");
	}

	@TenantIgnore
	@PostMapping("upload/excel/tem")
	public R<Boolean> uploadExcelTem(@RequestParam("file") MultipartFile file) throws IOException {

		Workbook wb = null;
		try {
			wb = WorkbookFactory.create(file.getInputStream());
		} catch (InvalidFormatException e) {
			return  R.fail("请使用正确的电梯模板导入电梯");
		}
		Sheet sheet = wb.getSheetAt(0);

		List<Map<String, Object>> readAll = PoiExcelUtil.readExcel(wb, 0, 0, 1, 0);
		if (readAll.size() == 0) {
			return R.fail("上传文件不能为空");
		}

		Boolean resultMap = elevatorDetailService.uploadExcelTem(readAll);
		return R.data(resultMap);
	}

}
